(ns util.io
  (:require clojure.java.io)
  (:import [java.io InputStream OutputStream
            ByteArrayInputStream ByteArrayOutputStream
            BufferedInputStream BufferedOutputStream
            FileInputStream FileOutputStream]
           [org.apache.commons.io IOUtils]))

;(set! *warn-on-reflection* true)

(defn bytes->stream [^bytes bytes]
  (ByteArrayInputStream. bytes))

(defn stream->bytes [^InputStream stream]
  (IOUtils/toByteArray stream))

(defn bytes-buffer
  ([]
    (ByteArrayOutputStream.))
  ([size]
    (ByteArrayOutputStream. size)))

(defn buffer->bytes [^ByteArrayOutputStream buffer]
  (.toByteArray buffer))

(defn buffer->stream [^ByteArrayOutputStream buffer]
  (-> buffer
    buffer->bytes
    bytes->stream))

(defn stream->string
  ([^InputStream stream]
    (IOUtils/toString stream))
  ([^InputStream stream ^String encoding]
    (IOUtils/toString stream encoding)))

(defn bytes->string
  ([^bytes bytes]
    (String. bytes))
  ([^bytes bytes ^String encoding]
    (String. bytes encoding)))

(defn string->bytes
  ([^String string]
    (.getBytes string))
  ([^String string ^String encoding]
    (.getBytes string encoding)))

(defn file->bytes [path]
  (with-open [stream (FileInputStream. (clojure.java.io/file path))]
    (stream->bytes stream)))

(defn bytes->file [bytes path]
  (with-open [stream (FileOutputStream. (clojure.java.io/file path))]
    (IOUtils/write bytes stream)))

